package com.wenjiang.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.injector.methods.SelectList;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.wenjiang.Repository.GoodRepository;
import com.wenjiang.common.constat.RedisKey;
import com.wenjiang.common.dto.PageParam;
import com.wenjiang.common.exception.FileException;
import com.wenjiang.common.lang.Result;
import com.wenjiang.common.vo.GoodDetail;
import com.wenjiang.common.vo.GoodInfo;
import com.wenjiang.entity.GoodIndex;
import com.wenjiang.entity.MallGood;
import com.wenjiang.entity.MallSecKillGood;
import com.wenjiang.mapper.MallGoodMapper;
import com.wenjiang.service.MallGoodService;
import com.wenjiang.service.MallSecKillGoodService;
import com.wenjiang.util.OSSUtils;
import com.wenjiang.util.RedisUtils;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.wenjiang.mapper.GoodIndexDao;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lwj
 * @since 2021-07-20
 */
@Service
@Transactional
public class MallGoodServiceImpl extends ServiceImpl<MallGoodMapper, MallGood> implements MallGoodService {

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    OSSUtils ossUtils;

    @Autowired
    GoodRepository goodRepository;

    @Autowired
    MallSecKillGoodService mallSecKillGoodService;

    @Autowired
    MallGoodMapper mallGoodMapper;

    //读写锁
    ReentrantReadWriteLock readWriteLock= new ReentrantReadWriteLock();



    //查找新最新上架的商品
    @Override
    public Result getNewGood() {

        // 直接存入一个数组
        Object data;

        //加入读锁
        readWriteLock.readLock().lock();
        try {
            //从redis拿 如果没有 才进行下一步
            if((data=redisUtils.get(RedisKey.mallNewGoodKey))!=null){
                return  Result.succ(data);
            }
        }finally {
            //读锁解锁
            readWriteLock.readLock().unlock();
        }

        //获取写锁
        readWriteLock.writeLock().lock();
        try {
            //判断其他线程是否写入了缓存了
            if((data=redisUtils.get(RedisKey.mallNewGoodKey))!=null){
                return  Result.succ(data);
            }
            //查询商品
            Page<MallGood> page = new Page<>(1, 12);
            Page<MallGood> pages = baseMapper.selectPage(page, new QueryWrapper<MallGood>().orderByDesc("good_create_time"));

            List<GoodInfo> newGoods = new ArrayList<>();

            pages.getRecords().forEach((item) -> {
                GoodInfo goodInfo = new GoodInfo();
                BeanUtil.copyProperties(item, goodInfo);
                newGoods.add(goodInfo);
            });

            // 设置一小时的过期时间
            redisUtils.set(RedisKey.mallNewGoodKey, newGoods,redisUtils.hour);
            return Result.succ(newGoods);

        }finally {
            readWriteLock.writeLock().unlock();
        }


    }


    /**
     * 获取商品的详情信息
     *
     * @param goodId
     * @return
     */
    @Override
    public Result getGoodById(Long goodId) {


        // 查询是否是特惠中的商品
        MallGood good = baseMapper.selectById(goodId);

        if (good.getGoodStatus() != 2) {
            return Result.succ(good);
        }


        GoodDetail goodDetail = new GoodDetail();
        BeanUtil.copyProperties(good, goodDetail);

        //查询对应的秒杀场次
        QueryWrapper<MallSecKillGood> mallSecKillGoodQueryWrapper = new QueryWrapper<>();
        mallSecKillGoodQueryWrapper.eq("good_id", goodId);
        mallSecKillGoodQueryWrapper.eq("is_end", 0);
        MallSecKillGood secKillGood = mallSecKillGoodService.getOne(mallSecKillGoodQueryWrapper);

        //查看是否可以秒杀了

        //获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        // 判断是否到达秒杀的时间
        if (currentTime.isAfter(secKillGood.getStartTime()) && currentTime.isBefore(secKillGood.getEndTime())) {
            goodDetail.setEnableSecKill(true);
        }


        goodDetail.setGoodSecKillPrice(secKillGood.getGoodSeckillPrice());
        goodDetail.setStartTime(DateUtil.formatLocalDateTime(secKillGood.getStartTime()));
        goodDetail.setEndTime(DateUtil.formatLocalDateTime(secKillGood.getEndTime()));

        return Result.succ(goodDetail);
    }


    @Override
    public Result getHotGood() {

        Object data= redisUtils.get(RedisKey.mallHotGoodKey);
        // 假设缓存为空
        if (data==null){
            //查询数据库
            //查询销量前10的商品
            QueryWrapper queryWrapper= new QueryWrapper();
            queryWrapper.orderByDesc("good_sell");
            //获取前10条数据有sql注入的分析
            queryWrapper.last("limit 12");
            List<MallGood> hotGood = mallGoodMapper.selectList(queryWrapper);
            data=hotGood;
            //更新缓存
            redisUtils.set(RedisKey.mallHotGoodKey, data);
        }

        return Result.succ(data);
    }


    @Override
    @Transactional
    public Result addGood(MallGood mallGood, MultipartFile file) {

        //添加商品图片到数据库 //拼接上传路径
        //判断文件是否为空
        if (file == null) {
            return Result.fail("上传的文件为空");
        }


        String name = file.getOriginalFilename();

        //文件后缀名
        String last = name.substring(name.lastIndexOf("."));

        if (!(last.equals(".jpg") || last.equals(".jpeg") || last.equals(".png"))) {
            return Result.fail("文件类型不匹配");
        }

        //设置商品创造时间
        mallGood.setGoodCreateTime(LocalDateTime.now());



        //插入数据的时候 保证 其他读的线程稍微进入阻塞  读取到最新的数据
        // 加入读写锁保证 最新商品的完全上架
        // 上入写锁
        readWriteLock.writeLock().lock();
        try {
            //往数据库插入数据
            save(mallGood);
            //获取文件名称 （轮播图id) +文件后缀名
            String filename = "goodImg/" + mallGood.getGoodId() + name.substring(name.lastIndexOf("."));
            String utl = ossUtils.getUrl(filename);
            try {
                ossUtils.upload(file.getBytes(), filename);
            } catch (Exception e) {
                throw new FileException();
            }
            mallGood.setGoodImgUrl(utl);
            // 更新数据库
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.set("good_img_url", utl);
            updateWrapper.eq("good_id", mallGood.getGoodId());
            update(updateWrapper);
            //清空缓存
            redisUtils.set(RedisKey.mallNewGoodKey, null);
        }finally {
            readWriteLock.writeLock().unlock();
        }




        // 添加索引
        GoodIndex goodIndex = new GoodIndex();
        BeanUtil.copyProperties(mallGood, goodIndex);
        goodRepository.save(goodIndex);


        return Result.succ("添加成功");
    }


    public MallGoodServiceImpl() {
        super();
    }

    @Override
    public Result getPageGood(PageParam pageParam) {
        //分页查询商品
        Page<MallGood> page = new Page<>((pageParam.getCurrentPage()), pageParam.getPageSize());

        Page<MallGood> page1 = page(page);


        return Result.succ(page1.getRecords());

    }


    @Override
    public Result getGoodCount() {
        int count = baseMapper.selectCount(null);

        return Result.succ(count);
    }

    @Override
    public Result setGood(MallGood mallGood) {

        // 判断该商品 是否出于秒杀中
        if (mallGood.getGoodStatus() == 2) {
            return Result.fail("该商品处于秒杀状态中 请先取消对该商品的秒杀");
        }

        // 修改该商品
        updateById(mallGood);

        //更新商品索引
        GoodIndex goodIndex = new GoodIndex();
        BeanUtil.copyProperties(mallGood, goodIndex);
        //更新索引
        goodRepository.save(goodIndex);


        return Result.succ("修改成功");

    }


    @Override
    public Result delGood(Long goodId) {


        //删除商品 （假删除）
        baseMapper.deleteById(goodId);
        //  同时删除es 的索引
        goodRepository.deleteById(goodId);


        //拼接redis上的key
        String hotGoodKey = RedisKey.mallHotGoodKey + goodId;
        String goodCount = RedisKey.mallGoodCount + goodId;

        //删除对用的key
        redisUtils.del(hotGoodKey, goodCount);

        return Result.succ("删除成功");
    }


    /**
     * 根据商品类别id 进行查找
     *
     * @param typeId
     * @return
     */
    @Override
    public Result getGoodByType(Long typeId) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type_id", typeId);

        List list = list(queryWrapper);

        return Result.succ(list);

    }

}
